/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.broker.controller;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.broker.commands.CommandExecutor;
import org.ourgrid.broker.commands.SchedulerData;
import org.ourgrid.broker.controller.processors.UtilProcessor;
import org.ourgrid.broker.dao.BrokerMessageProcessorDAO;
import org.ourgrid.broker.scheduler.SchedulerIF;
import org.ourgrid.broker.scheduler.extensions.GenericTransferHandle;
import org.ourgrid.broker.scheduler.extensions.GenericTransferProgress;
import org.ourgrid.broker.scheduler.extensions.IncomingHandle;
import org.ourgrid.broker.scheduler.extensions.OutgoingHandle;
import org.ourgrid.common.interfaces.MessageProcessor;
import org.ourgrid.common.interfaces.WorkerClient;
import org.ourgrid.common.interfaces.to.MessageHandle;

import br.edu.ufcg.lsd.commune.api.InvokeOnDeploy;
import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.ContainerID;
import br.edu.ufcg.lsd.commune.processor.filetransfer.IncomingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.OutgoingTransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.TransferHandle;
import br.edu.ufcg.lsd.commune.processor.filetransfer.TransferProgress;

/**
 */
public class WorkerClientController implements WorkerClient {

	private ServiceManager serviceManager;

	@InvokeOnDeploy
	public void init(ServiceManager serviceManager) {
		this.serviceManager = serviceManager;
	}
	
	public void sendMessage(MessageHandle handle) {
		
		ContainerID senderServiceID = serviceManager.getSenderServiceID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
		if (scheduler != null) {
			
			MessageProcessor<MessageHandle> processor = getBrokerMessageProcessorDAO().getMessageProcessor(
					handle.getActionName());
			
			if (processor != null) {
				processor.process(handle, serviceManager);
			} else {
				
				outputCommands = scheduler.sendMessage(handle);
				if (outputCommands != null) {
					CommandExecutor.getInstance().execute(outputCommands, serviceManager);
				}
			}
		} else {
			//TODO 
		}
	}

	public void outgoingTransferCancelled(OutgoingTransferHandle handle, long amountWritten) {
		
		ContainerID senderServiceID = handle.getDestinationID().getServiceID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.outgoingTransferCancelled(getHandle(handle), amountWritten);
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}	
		}
	}

	public void outgoingTransferCompleted(OutgoingTransferHandle handle, long amountWritten) {
		
		ContainerID senderServiceID = handle.getDestinationID().getServiceID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.outgoingTransferCompleted(getHandle(handle), amountWritten);
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}	
		}
	}

	public void outgoingTransferFailed(OutgoingTransferHandle handle, Exception failCause, long amountWritten) {
		
		ContainerID senderServiceID = handle.getDestinationID().getServiceID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.outgoingTransferFailed(getHandle(handle), failCause.getMessage(), amountWritten);
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}	
		}
	}

	public void incomingTransferCompleted(IncomingTransferHandle handle, long amountWritten) {
		
		ContainerID senderServiceID = handle.getSenderID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.incomingTransferCompleted(getHandle(handle), amountWritten);
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}
		}
	}

	public void incomingTransferFailed(IncomingTransferHandle handle, Exception failCause, long amountWritten) {
		
		ContainerID senderServiceID = handle.getSenderID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.incomingTransferFailed(getHandle(handle), failCause.toString(), amountWritten);
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}
		}
	}

	public void transferRejected(OutgoingTransferHandle handle) {
		
		ContainerID senderServiceID = handle.getDestinationID().getServiceID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.transferRejected(getHandle(handle));
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}
		}
	}

	public void updateTransferProgress(TransferProgress transferProgress) {
		
		ContainerID senderServiceID = serviceManager.getSenderServiceID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.updateTransferProgress(getTransferProgress(transferProgress));
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}
		}
	}

	public void transferRequestReceived(IncomingTransferHandle handle) {
		
		ContainerID senderServiceID = handle.getSenderID().getContainerID();
		SchedulerIF scheduler = getScheduler(senderServiceID);
		
		if (scheduler != null) {
			List<SchedulerData> outputCommands = new ArrayList<SchedulerData>();
			outputCommands = scheduler.transferRequestReceived(getHandle(handle));
			
			if (outputCommands != null) {
				CommandExecutor.getInstance().execute(outputCommands, serviceManager);
			}
		}
	}
	
	private SchedulerIF getScheduler(ContainerID senderServiceID) {
		return UtilProcessor.getScheduler(serviceManager, senderServiceID);
	}
	
	private BrokerMessageProcessorDAO getBrokerMessageProcessorDAO() {
		return serviceManager.getDAO(BrokerMessageProcessorDAO.class);
	}
	
	private OutgoingHandle getHandle(OutgoingTransferHandle handle) {
		return new OutgoingHandle(handle.getId(), handle.getLocalFileName(), handle.getDestinationFileName(), 
				handle.getDescription(), handle.getDestinationID().toString(), 
				handle.getDestinationID().getContainerID().toString());
	}
	
	private IncomingHandle getHandle(IncomingTransferHandle handle) {
		return new IncomingHandle(handle.getId(), handle.getLocalFileName(), handle.getDestinationFileName(), 
				handle.getFileSize(), handle.getDescription(), handle.getOppositeID().toString());
	}
	
	private GenericTransferProgress getTransferProgress(TransferProgress progress) {
		
		TransferHandle handle = progress.getHandle();
		
		GenericTransferHandle genericHandle = new GenericTransferHandle(handle.getId(), handle.getLocalFileName(),
				handle.getDestinationFileName(), handle.getDescription());
		
		return new GenericTransferProgress(genericHandle, progress.getFileName(), progress.getFileSize(),
				progress.getNewStatus().toString(), progress.getAmountWritten(), progress.getProgress(),
				progress.getTransferRate(), progress.isOutgoing());
	}
}
